<template>
    <view class="store-manage position-r">
        <image class="store-manage__bg full-w position-a left0 top0" src="@/static/store_bg.png" mode="widthFix"></image>
        <u-navbar
            :autoBack="true"
            leftIconColor="#ffffff"
            :titleStyle="{ color: '#ffffff',}"
            bgColor="rgba(0,0,0,0)"
            title="门店管理"
        >
        </u-navbar>

        <view class="store-manage__header  mr-v-24 position-r">
            <view class="border8 pd-l-24 bg-white">
                <u--form
                    labelWidth="100"
                    labelPosition="left"
                    :model="form"
                >
                    <u-form-item
                        label="门店名称"
                        prop="name"
                        borderBottom
                    >
                        <u--input
                            v-model.trim="form.name"
                            border="none"
                            color="#B3ADAE"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请输入门店名称"
                            @change="search"
                        ></u--input>
                    </u-form-item>
                    <u-form-item
                        label="所属商户"
                        prop="merchantName"
                        borderBottom
                    >
                        <u--input
                            v-model.trim="form.merchantName"
                            border="none"
                            color="#B3ADAE"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请输入所属商户"
                            @change="search"
                        ></u--input>
                    </u-form-item>
                </u--form>
            </view>
            
        </view>
          
        
          
        <view class="store-manage__body mr-v-24">
            <u-checkbox-group class="full-w" v-model="checkedList" @change="checkboxChange">
                <view class="store-item border8 pd-v-24 bg-white mr-t-20 full-w box" v-for="(item,index) in list" :key="'check'+index">
                    <view class="store-item__body pd-t-32 pd-b-24 border-b">
                        <view class="font32 lh-44 bold color-default">
                            {{item.name}}
                        </view>
                        <view class="mr-t-12 font26 lh-36 color-note">
                            设备数量  {{item.deviceCount || 0}}
                        </view>
                        <view class="mr-t-20 font26 lh-36 color-default">
                            {{item.merchantName}} 
                            {{item.repairPhone}}
                        </view>
                        
                    </view>

                    <view class="store-item__footer pd-h-16 flex flex-center">
                        <view class="flex-1">
                            <u-checkbox
                                shape="circle"
                                activeColor="#35BE65"
                                :name="item.id"
                            >
                            </u-checkbox>
                        </view>


                        <!-- <template v-if="item.isAlly == 0"> -->
                            <u-button plain :customStyle="{height:'60rpx',marginLeft:'16rpx',width:'152rpx'}" shape="circle" color="#35BE65"  text="删除" @click="deleteItem(item,index)"></u-button>

                            <u-button plain :customStyle="{height:'60rpx',marginLeft:'16rpx',width:'152rpx'}" shape="circle" color="#35BE65"  text="修改" @click="editItem(item,index)"></u-button>

                            <u-button plain :customStyle="{height:'60rpx',marginLeft:'16rpx',width:'152rpx'}" shape="circle" color="#35BE65"  text="添加设备" @click="addItem(item,index)"></u-button>
                        <!-- </template> -->


                        <!-- <template v-else-if="item.isAlly == 1"> -->
                            <u-button plain :customStyle="{height:'60rpx',marginLeft:'16rpx',width:'152rpx'}" shape="circle" color="#35BE65"  text="详情" @click="goDetail(item,index)"></u-button>
                        <!-- </template> -->
                        
                    </view>
                    
                    
                </view>
            </u-checkbox-group>
        </view>
          

        <view class="store-manage__footer position-f full-w box pd-v-24 pd-h-16 bg-white">
            <view class="flex flex-center">
                <view class="flex-1">
                    <u-checkbox-group class="full-w" v-model="allChecked" @change="allCheckedChange">
                        <u-checkbox
                            shape="circle"
                            activeColor="#35BE65"
                            :name="'all'"
                            label="全选"
                        >
                        </u-checkbox>
                    </u-checkbox-group>
                </view>

                <u-button type="primary" :customStyle="{height:'76rpx',marginLeft:'16rpx',width:'276rpx'}" shape="circle" color="#272636"  text="修改门店充电费用" @click="costChange"></u-button>
                
                <u-button type="primary" :customStyle="{height:'76rpx',marginLeft:'16rpx',width:'208rpx'}" shape="circle" color="#35BE65"  text="新增门店" @click="storeAdd"></u-button>
            </view>
              
              
        </view>


        <u-popup :show="addPopupShow" closeable @close="close" mode="bottom">
            <view class="pd-v-24 pd-b-12 add-popup">
                <view class="add-popup__header txt-center pd-t-36 font32 lh-44 bold position-r pd-v-150 line1">
                    {{activeItem.name}}

                    <view class="add position-a font28 lh-40" @click="scanCode">
                        +添加
                    </view>
                      
                </view>

                <view class="add-popup__body">
                  <view class="shadow mr-h-24 border-default border8" >
                    <scroll-view style="max-height:600rpx;width:100%;min-height:400rpx;" scroll-y>
                      <u--form
                        :model="addForm"
                        ref="addUForm"
                        :rules="rules"
                      >
                        <view class="flex pd-h-8 pd-v-12 border-b flex-center" v-for="(item,index) in addForm.deviceList" :key="index+'[iii]'">
                          <view class="w60 font24 lh-36 txt-center ">{{ index+1 }}</view>
                          <view class="flex-1 flex flex-center">
                            <view class="flex-1">{{item.serialNumber}}</view>
                            <view class="flex-1">
                              <u-form-item  :prop="`deviceList.${index}.deviceName`"> 
                                <u--input v-model.trim="item.deviceName" placeholder="设备名称" 
                                    type="text"
                                    :customStyle="{padding:'8rpx 8rpx'}"
                                    fontSize="24rpx"
                                    inputAlign="center"></u--input>
                              </u-form-item>
                            </view>
                          </view>
                          <view class="mr-v-8" @click="removeDevice(index)">
                            <u-icon name="close-circle"></u-icon>
                          </view>
                        </view>
                      </u--form>
                    </scroll-view>
                  </view>
                </view>
                
                <view class="add-popup__footer flex flex-j-around">
                    <u-button type="primary" :customStyle="{height:'88rpx',marginLeft:'16rpx',width:'300rpx',color:'#333436'}" shape="circle" color="#F0F0F0"  text="取消" @click="close"></u-button>
                    
                    <u-button type="primary" :customStyle="{height:'88rpx',marginLeft:'16rpx',width:'300rpx'}" shape="circle" color="#35BE65"  text="确定" @click="submit"></u-button>
                </view>
                  
            </view>
		    </u-popup>

        <u-overlay :show="showModal"  @click="hideModal">
          <view class="full-w full-h flex flex-center flex-j-center">
            <view class="bg-white pd-v-20 pd-h-20 border8"  @tap.stop>
              <view class="font32 lh-38 color-default txt-center bold">充电费用</view>
              <u--form class="mr-t-20" :rules="costRules" :model="costForm" ref="costFormRef">
                  <view class=" font28 lh-28 color-default">
                      服务费
                  </view>
                  <scroll-view style="max-height:600rpx;width:100%;min-height:400rpx;" scroll-y>
                    <view class="flex mr-t-10 position-r" v-for="(item,index) in costForm.serviceChargeList" :key="'in'+index">
                        <view class="flex-1">
                            <u-form-item
                                :prop="`serviceChargeList.${index}.startPower`"
                            >
                                <u--input
                                    v-model.trim="item.startPower"
                                    border="none"
                                    disabled
                                    type="text"
                                    :customStyle="{padding:'8rpx 8rpx',background:'#f1f1f1'}"
                                    placeholder="功率"
                                    fontSize="24rpx"
                                    color="#C0C4CC"
                                    inputAlign="center"
                                ></u--input>
                            </u-form-item>
                        </view>
                        <text class="font24 lh-40 color-default pd-v-8 mr-t-32">
                            瓦-
                        </text>
                          
                        <view class="flex-1">
                            <u-form-item
                                :prop="`serviceChargeList.${index}.endPower`"
                                @click="chooseEndPower(item)"
                            >
                                <u--input
                                    v-model.trim="item.endPower"
                                    border="none"
                                    readonly
                                    :customStyle="{padding:'8rpx 8rpx',background:'#F5F7FA'}"
                                    placeholder="功率"
                                    fontSize="24rpx"
                                    color="f3f3f3"
                                    type="text"
                                    inputAlign="center"
                                ></u--input>
                            </u-form-item>
                        </view>
                        <text class="font24 lh-40 color-default pd-v-8 mr-t-32">
                            瓦
                        </text>
                        <view class="flex-1 mr-l-40">
                            <u-form-item
                                  :prop="`serviceChargeList.${index}.price`"
                            >
                                <u--input
                                    v-model.trim="item.price"
                                    border="none"
                                    :customStyle="{padding:'8rpx 8rpx',background:'#F5F7FA',color:'#C0C4CC'}"
                                    placeholder="价格(元小时)"
                                    fontSize="24rpx"
                                    color="f3f3f3"
                                    type="digit"
                                    inputAlign="center"
                                ></u--input>
                            </u-form-item>
                        </view>

                        <view class="close-btn pd-v-10 pd-h-10 position-a" v-if="index>0" @click="remove(index)">
                            <u-icon name="close-circle-fill" size="18" color="#4c4c4c"></u-icon>
                        </view>
                          
                    </view>
                  </scroll-view>
                  <view class="mr-t-30 pd-v-24 flex flex-center flex-j-center">
                      <u-button plain :customStyle="{height:'76rpx',width:'600rpx',borderStyle:'dashed'}" color="#999390"  text="新增 +" @click="add"></u-button>
                  </view>
                    
              </u--form>

              <view class="mr-t-40 flex flex-center flex-j-center">
                    <u-button shape="circle"  :customStyle="{height:'88rpx',width:'600rpx'}" color="#35BE65"  text="确认" @click="costSubmit"></u-button>
              </view>
            </view>
          </view>
        </u-overlay>
          
        <u-picker :show="costShow" :columns="getRange(activeCostItem?.startPower)" @close="costClose" @cancel="costCancel" @confirm="costConfirm"></u-picker>
    </view>
</template>

<script setup>
import { useStore } from '@/store/index.js';
import { ref, reactive, onMounted, nextTick,watch} from 'vue';
import { onLoad, onReady, onShow,onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';

import { storeList, storeUpdate, storeQueryById,storeDelete,deviceAdd } from '@/api/proxy.js'

const store = useStore();
const form = ref({
    name: '',
    merchantName: ''
});


const addUForm = ref(null);
const addForm = ref({
  deviceList:[]
})


const costForm = ref({
    serviceChargeList:[{
        startPower:'0',
        endPower:'',
        price:''
    }]
});


const costRules = ref({
    serviceChargeList: [
        {
            required: true,
            message: '请输入服务费',
            trigger: ['blur','change']
        }
    ],
})

const costFormRef = ref(null);

const costShow = ref(false);

const timer = ref(null);
const checkedList = ref([]);
const allChecked = ref([])
const addPopupShow = ref(false);
const list = ref([])
const total = ref(0);
const params = ref({
    pageNum: 1,
    pageSize: 10
})
const activeCostItem = ref({})
const activeItem = ref({})
const rules = ref({
  deviceList: [
        {
            required: true,
            message: '请录入设备',
            trigger: ['blur','change']
        }
    ],
})

const showModal = ref(false)


watch(checkedList,(newVal,oldVal) => {
  if(newVal.length) { 
    let checkList = [];
    list.value.forEach(item => {
        checkList.push(item)
    })

    if(checkList.length == newVal.length) {
      allChecked.value.push('all')
    } else {
      allChecked.value = []
    }
  }
  
  
},{ deep: true })



watch(costForm.value.serviceChargeList,(newVal,oldVal) => {
    // console.log(JSON.parse(JSON.stringify(oldVal)))
    // console.log(JSON.parse(JSON.stringify(newVal)))

    refreshStartPower();
},{ deep: true })

onReady(() => {
    
})

onShow(() => {
    if(list.value.length == 0) {
      params.value.pageNum  = 1
      getStoreList()
    }
})

onLoad(() => {
})

onPullDownRefresh(() => {
    console.log('下拉刷新')
    params.value.pageNum  = 1
    checkedList.value = [];
    allChecked.value = []
    list.value = [];
    getStoreList()
})


onReachBottom(() => {
    if(list.value.length < total.value) {
        params.value.pageNum++;
        getStoreList()
    }
})

const getRange = (start) => {
    let rangeList = [];
    for (let i = 0; i <= 3500; i+=50) {
        if(start || start == 0) {
            if(i > start) {
            rangeList.push(i);
            }
        } else {
            rangeList.push(i);
        }
    
    }
    console.log(rangeList)
    return [rangeList];
}

const setCostRules = () => {
    costFormRef.value.setRules(rules.value);
    costForm.value.serviceChargeList.forEach((ele, index) => {
        rules.value[`serviceChargeList.${index}.startPower`] = {
            message: '请输入功率',
            trigger: ['blur','change'],
            transform: (value) => {
                return String(value);
            }
        }
        rules.value[`serviceChargeList.${index}.endPower`] = {
            required: true,
            message: '请输入功率',
            trigger: ['blur','change'],
            transform: (value) => {
                return String(value);
            }
        }
        rules.value[`serviceChargeList.${index}.price`] = {
            required: true,
            message: '请输入价格',
            trigger: ['blur','change'],
            transform: (value) => {
                return String(value);
            }
        }
    })
}
const setRules = () => {
    addUForm.value.setRules(rules.value);
    addForm.value.deviceList.forEach((ele, index) => {
        rules.value[`deviceList.${index}.deviceName`] = {
            required: true,
            message: '请输入设备名称',
            trigger: ['blur','change'],
            transform: (value) => {
                return String(value);
            }
        }
    })
}
const getStoreList = () => {
    uni.showLoading({
        title: '加载中...',
        mask: true
    });


    storeList({...form.value,...params.value}).then(res => {
        uni.hideLoading()
        console.log(res)
        uni.stopPullDownRefresh()
        if(res.code == 200) {
            list.value = [...list.value,...res.rows]
            total.value = res.total
        }
    }).catch(err => {
        uni.hideLoading()
        uni.stopPullDownRefresh()
        console.log(err)
    })
}


const search = () => {
    clearTimeout(timer.value);
    timer.value = setTimeout(() => {
        list.value = [];
        params.value.pageNum = 1;
        getStoreList()
    },1000)
        
}

const checkboxChange = (e) => {
    console.log(e)
    let checkList = [];
    list.value.forEach(item => {
        checkList.push(item)
    })

    if(checkList.length == e.length) {
      allChecked.value.push('all')
    } else {
      allChecked.value = []
    }
}

const costChange = () => {
    if(checkedList.value.length) {
      showModal.value = true
      
      costForm.value.serviceChargeList = [{
        startPower: '0',
        endPower: '',
        price: ''
      }]

      setCostRules()
    } else {
        uni.showToast({
            title: '请选择门店',
            icon: 'none'
        })
    }
}


const allCheckedChange = (e) => {
    if(e.length) {
        checkedList.value = [];

        list.value.forEach(item => {
            checkedList.value.push(item.id)
            
        })
    } else {
        checkedList.value = [];
    }
}

const close = () => {
    addPopupShow.value = false;
    addForm.value.deviceList = []
}


const submit = () => { 
  console.log(addUForm)
    if(addForm.value.deviceList.length == 0) {
        uni.showToast({
            title: '请录入设备',
            icon: 'none'
        })
        return
    }
    addUForm.value.validate().then(async res => { 
      addDevice(addForm.value.deviceList[0])
      uni.showLoading({ 
        title: '添加中...',
        mask: true
      })
    })
}


const addDevice = (item) => { 
  deviceAdd({
      name: item.deviceName,
      number:item.serialNumber,
      storeId:activeItem.value.id,
  }).then(res => { 
    if(res.code == 200) {
      let index = addForm.value.deviceList.findIndex(ele => ele.serialNumber == item.serialNumber);
      addForm.value.deviceList.splice(0,1)
      if(addForm.value.deviceList.length == 0) {
        console.log(123)
        uni.hideLoading()
        uni.showToast({
            title: '添加完毕',
            icon: 'none',
            duration: 2000
        })
        // close();
        return;
      } else {
        console.log('ccc')
        addDevice(addForm.value.deviceList[0])
      }
      
    } else {
      uni.hideLoading()
      uni.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  })
}


const addItem = (item) => {
    activeItem.value = item
    addPopupShow.value = true;
    setRules()
}

const editItem = (item) => {
    uni.navigateTo({
        url: '/sub_proxy/pages/storeAdd/storeAdd?storeId='+item.id
    })
}

const deleteItem = (item,index) => {
    uni.showModal({
        title: '提示',
        content: '确定删除该门店吗？',
        success: function (res) {
            if (res.confirm) {
                console.log('用户点击确定');
                storeDelete(item.id).then(res => {
                    if(res.code == 200) {
                        uni.showToast({
                            title: '删除成功',
                            icon: 'none'
                        })
                        checkedList.value = []
                        allChecked.value = []
                        list.value.splice(index,1)
                    }else {
                              uni.showToast({
                                  title: res.msg,
                                  icon: 'none'
                              })
                          }
                })
            } else if (res.cancel) {
                console.log('用户点击取消');
            }
        }
    });
}

const scanCode = () => {
    uni.scanCode({
        success: function (res) {
            console.log('条码类型：' + res.scanType);
            console.log('条码内容：' + res.result);
            let url = res.result;
            let equipmentReg = /equipment\/([^\/]+)/
            let equipmentMatch = url.match(equipmentReg)
            if(equipmentMatch && equipmentMatch[1]) {
                let hasDevice = addForm.value.deviceList.find(ele => ele.serialNumber == equipmentMatch[1]);
                if(hasDevice) {
                    uni.showToast({
                        title:'该设备已存在，请勿重复添加',
                        icon:'none'
                    })
                    return;
                }
                addForm.value.deviceList.push({
                    deviceName: '',
                    serialNumber: equipmentMatch[1]
                })
                setRules()
            } else {
                uni.showToast({
                    title:'请扫描正确的二维码',
                    icon:'none'
                })
            }
        }
    });
}

const storeAdd = () => {
    uni.navigateTo({
        url: '/sub_proxy/pages/storeAdd/storeAdd'
    })
}

const goDetail = (item) => {
    uni.navigateTo({
        url: '/sub_proxy/pages/storeDetail/storeDetail?storeId='+item.id
    })
}

const removeDevice = (index) => {
    addForm.value.deviceList.splice(index,1)
    setRules()
}


const add = () => {
    costForm.value.serviceChargeList.push({
        startPower:'0',
        endPower:'',
        price:''
    })
    
    
    setCostRules()
    refreshStartPower()
}



const remove = (index) => {
  costForm.value.serviceChargeList.splice(index,1)
}


const chooseEndPower = (item) => {
    activeCostItem.value = item;
    costShow.value = true;
}


const costClose = () => {
    costShow.value = false;
}

const costCancel = () => { 
  costShow.value = false;
}


const costConfirm = (e) => {
    let index = costForm.value.serviceChargeList.findIndex(item => item == activeCostItem.value);
    activeCostItem.value.endPower = String(e.value[0]);
    costShow.value = false;
    refreshStartPower()
}


const refreshStartPower = () => {
    costForm.value.serviceChargeList.forEach((item, index) => {
        if(index == 0) {
            item.startPower = '0';
        } else {
            item.startPower = costForm.value.serviceChargeList[index - 1].endPower;
        }

    })
}

const hideModal = () => { 
  showModal.value = false
}


const costSubmit = () => {
    console.log(costForm.value.serviceChargeList)
    costFormRef.value.validate().then(res => {

        let item = list.value.find(item => item.id == checkedList.value[0])

        uni.showLoading({
            title:'修改中...'
        })
        editStore(item)
        console.log(params,'params')
        
    }).catch(err => {
        console.log(err,'eeeeeeeeeeeeeeeee')
    })
}


const editStore = (item) => { 
  let params = {
      name: item.name,
      detailedAddress: item.detailedAddress,
      birthPlace: item.birthPlace,
      image: item.image,
      serviceChargeList: costForm.value.serviceChargeList,
      chargeFee:item.chargeFee,
      repairPhone:item.repairPhone,
      id: item.id
  }
  storeUpdate(params).then(res => { 
    if(res.code == 200) {
      let index = checkedList.value.findIndex(ele => ele == item.id);
      checkedList.value.splice(0,1)
      if(checkedList.value.length == 0) {
        uni.hideLoading()
        uni.showToast({
            title: '修改完毕',
            icon: 'none',
            duration: 2000
        })
        
        showModal.value = false
        params.value.pageNum  = 1
        checkedList.value = [];
        allChecked.value = []
        list.value = [];
        getStoreList()
        // close();
        
      } else {
        console.log('ccc')
        let item = list.value.find(item => item.id == checkedList.value[0])
        editStore(citem)
      }
      
    } else {
      uni.hideLoading()
      uni.showToast({
        title: res.msg || item.name+'修改失败',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

</script>

<style scoped lang="scss">
.store-manage {
    background: #F7F7F7;
    min-height:100vh;

    .store-manage__header {
        z-index: 2;
        padding-top:196rpx;
        
    }

    .store-manage__body {
        z-index: 2;
        padding-bottom:220rpx;

        .store-item {
            .border-b {
                border-bottom:1px solid #EEEEEE;
            }
        }
    }

    .w60 {
        width: 60rpx;
    }

    
    .border-b {
        border-bottom:1px solid #EEEEEE;
    }

    .store-manage__footer {
        box-shadow: 0px -1px 2px 0px rgba(0,0,0,0.05);
        z-index: 10;
        left:0;
        bottom:0;
        height: 176rpx;
    }
    

    .add-popup {
        .add {
            left:24rpx;
            top:40rpx;
        }
    }

    
    ::v-deep .u-form-item__body__right__message {
        margin-left:0!important;
    }

    .close-btn {
        right:-20rpx;
        top:0;
        z-index: 9999;
    }

    .image-close-btn {
        right: -20rpx;
        top: -20rpx;
        z-index: 9999;
    }
}
</style>
